package com.incross.itracker.receiver;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.incross.itracker.ITracker;
import com.incross.itracker.util.BKLog;
import com.incross.itracker.util.CommonUtils;


public class InstallReferrerReceiver extends BroadcastReceiver {
	

	@Override
	public void onReceive(Context context, Intent intent) {
		
		BKLog.i("InstallReceiver onReceive - ");
		
		String referrer = "";
		String encodedReferrer = "";
		Bundle extras = intent.getExtras();
		if(extras != null){
			referrer = extras.getString("referrer");
			
			if(referrer != null && !referrer.equals("")) {
				try {
					encodedReferrer = URLEncoder.encode(referrer, "UTF-8");
				} catch(UnsupportedEncodingException e) {
					encodedReferrer = referrer;
					e.printStackTrace();
				}
				
				String savedReferrer = CommonUtils.getStringPreference(context, ITracker.KEY_INSTALL_REFERRER);
				if(savedReferrer == null || savedReferrer.equals("")) {
					// Install referrer not saved(or removed)
					CommonUtils.setStringPreference(context, ITracker.KEY_INSTALL_REFERRER, encodedReferrer);
				} else {
					if(!savedReferrer.equals(encodedReferrer)) {
						CommonUtils.setStringPreference(context, ITracker.KEY_INSTALL_REFERRER, encodedReferrer);
					}
				}
				Toast.makeText(context, "Referrer received : " + referrer, Toast.LENGTH_SHORT).show();
				BKLog.i("Received Referrer : " + referrer);
				BKLog.i("Referrer after encode : " + encodedReferrer);
			}
		} else {
			Toast.makeText(context, "Referrer receiver received but empty referrer!!", Toast.LENGTH_SHORT).show();
			BKLog.e("ReferrerReceiver message received. but empty(or null) referrer.");
		}
	}

}
